import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Tabs } from 'antd';
import UploadAndShow from './uploadAndShow';
import PersonalDetail from './personalDetails';
import style from './index.module.css';
import { useSelector, useDispatch } from 'react-redux';
import { toggleDeleteTabsList } from '@/redux/home/scientificResearchManagementSystem';

const defaultPanes = new Array(1).fill(null).map((_, index) => {
  const id = String(index + 1);
  return {
    label: `Tab ${id}`,
    children: <UploadAndShow />,
    key: id,
    closable: index !== 0,
  };
});

export default function ScientificResearchManagementSystem() {
  const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
  const [items, setItems] = useState(defaultPanes);
  const newTabIndex = useRef(0);
  const dispatch = useDispatch();
  const tabsList = useSelector((state) => state.scientificResearchManagementSystem.tabsList);
  const [nowtabs, setNowtabs] = useState([]);

  useEffect(() => {
    if (tabsList && tabsList.length > 0) {
      tabsList.forEach((item) => {
        if (!nowtabs.includes(item)) {
          setNowtabs([...nowtabs, item]);
          add(item)
        }
      });
    }
  }, [tabsList]);

  const onChange = (key) => {
    setActiveKey(key);
  };

  const add = (id) => {
    if (!id) {
      message.error("无效的ID");
      return;
    }
    const newActiveKey = `newTab${newTabIndex.current++}`;
    setItems([
      ...items,
      {
        label: '个人详细信息展示',
        children: <PersonalDetail id={id} />,
        key: newActiveKey,
        closable: true,
        infoId: id,
      },
    ]);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey) => {
    const targetIndex = items.findIndex((pane) => pane.key === targetKey);
    if (targetIndex === 0) {
      message.info("该标签页不可删除");
      return; // 第一个标签页不可删除
    }

    const deleteItem = items.filter((pane) => pane.key == targetKey);
    ;
    setNowtabs(nowtabs.filter((id) => id !== deleteItem[0].infoId));
    dispatch(toggleDeleteTabsList(deleteItem[0].infoId));


    const newPanes = items.filter((pane) => pane.key !== targetKey);
    if (newPanes.length && targetKey === activeKey) {
      const lastIndex = newPanes.length - 1;
      const newIndex = targetIndex > lastIndex ? lastIndex : targetIndex;
      setActiveKey(newPanes[newIndex].key);
    }
    setItems(newPanes);
  };

  const onEdit = (targetKey, action) => {
    if (action === 'add') {
      add('defaultId'); // 假设有一个默认ID或者从其他地方获取
    } else {
      remove(targetKey);
    }
  };

  return (
    <div>
      <Tabs
        hideAdd
        onChange={onChange}
        activeKey={activeKey}
        type="editable-card"
        onEdit={onEdit}
        items={items}
      />
    </div>
  );
}